import os
import pandas as pd
import matplotlib.pyplot as plt
import datetime
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import roc_auc_score, make_scorer
from xgboost import XGBClassifier
from sklearn.preprocessing import StandardScaler
from my_utils.log import Logger
import joblib
from imblearn.over_sampling import SMOTE

plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['font.size'] = 15

#---------------------------------------------
#32222222222222222222222222222222222222222222
#😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛
#
#    SMOTE        和       xgboost
#
#😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛😛
#23333333333333333333333333333333333332222222
#---------------------------------------------

# 1 定义人才流失模型类 配置日志 获取数据源
class BrainDrainModel:
    def __init__(self, path):
        logfile_name = 'train_' + datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        self.logfile = Logger('../', logfile_name).get_logger()
        self.data_source = pd.read_csv(path)


# 2 特征工程
def feature_engineering(data, logger):
    feature_data = data.copy()
    feature_data.drop(['EmployeeNumber', 'Over18', 'StandardHours'], axis=1, inplace=True)
    feature_data = pd.get_dummies(feature_data, drop_first=True)
    #feature_columns = feature_data.columns.tolist()
 #    feature_columns=['Age', 'DistanceFromHome', 'Education', 'EnvironmentSatisfaction', 'JobInvolvement', 'JobLevel',
 # 'JobSatisfaction', 'MonthlyIncome', 'NumCompaniesWorked', 'PercentSalaryHike', 'PerformanceRating',
 # 'RelationshipSatisfaction', 'StockOptionLevel', 'TotalWorkingYears', 'TrainingTimesLastYear', 'WorkLifeBalance',
 # 'YearsAtCompany', 'YearsInCurrentRole', 'YearsSinceLastPromotion', 'YearsWithCurrManager',
 # 'BusinessTravel_Travel_Frequently', 'BusinessTravel_Travel_Rarely',
 # 'EducationField_Life Sciences', 'EducationField_Marketing', 'EducationField_Medical',
 # 'EducationField_Other', 'EducationField_Technical Degree',
 # 'JobRole_Human Resources', 'JobRole_Laboratory Technician', 'JobRole_Manager', 'JobRole_Manufacturing Director', 'JobRole_Research Director',
 # 'JobRole_Research Scientist', 'JobRole_Sales Executive', 'JobRole_Sales Representative', 'MaritalStatus_Married',
 # 'MaritalStatus_Single', 'OverTime_Yes']
    feature_columns=['Age', 'EnvironmentSatisfaction', 'JobInvolvement', 'JobLevel', 'JobSatisfaction', 'PercentSalaryHike', 'PerformanceRating', 'StockOptionLevel', 'TotalWorkingYears', 'TrainingTimesLastYear', 'WorkLifeBalance', 'YearsInCurrentRole', 'YearsSinceLastPromotion', 'MaritalStatus_Married', 'MaritalStatus_Single', 'OverTime_Yes']
    return feature_data, feature_columns


# xgboost
def model_train_xgboost(data, features, logger):
    # 1.数据划分
    x = data[features]
    y = data['Attrition']
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=23)
    #2.网格化搜索与交叉验证
    param_grid = {
        'n_estimators': [120, 310,300,410],
        'max_depth': [3, 9,8,7],
        'learning_rate': [0.04, 0.06, 0.05],
        'random_state': [18, 21, 22,61]
    }
    model = XGBClassifier()
    grid_search = GridSearchCV(model, param_grid, cv=5)
    grid_search.fit(x_train, y_train)
    logger.info(f'网格化搜索参数：{grid_search.best_params_}')
    # 3.模型实例化
    model = XGBClassifier()
    # 4.模型训练
    model.fit(x_train, y_train)
    # 5.模型评估
    y_score = model.predict_proba(x_test)[:, 1]
    logger.info(f"xgboost模型AUC:{roc_auc_score(y_test, y_score)}")
    # 6.模型保存
    model_path = "../model/xgboost_20251027.pkl"
    joblib.dump(model, model_path)
    logger.info(f"模型保存成功，保存路径{os.path.abspath(model_path)}")
def model_train_SMOTE(data,features,logger):
    # 1.数据划分
    x = data[features]
    y = data['Attrition']

    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=23)
    smote = SMOTE(random_state=42)
    x_train, y_train = smote.fit_resample(x_train, y_train)
    #2.网格化搜索与交叉验证
    param_grid = {
        'n_estimators': [120, 310, 300, 410],
        'max_depth': [3, 9, 8, 7],
        'learning_rate': [0.04, 0.06, 0.05],
        'random_state': [18, 21, 22, 61]
    }
    model = XGBClassifier()
    grid_search = GridSearchCV(model, param_grid, cv=5)
    grid_search.fit(x_train, y_train)
    logger.info(f'网格化搜索参数：{grid_search.best_params_}')
    #model = SMOTE()
    #4.使用最佳参数训练模型
    model=grid_search.best_estimator_
    #model.fit(x_train, y_train)
    # 5.模型评估
    y_score = model.predict_proba(x_test)[:, 1]
    logger.info(f"xgboost模型AUC:{roc_auc_score(y_test, y_score)}")
    # 6.模型保存
    model_path = "../model/xgboost_20251027.pkl"
    joblib.dump(model, model_path)
    logger.info(f"模型保存成功，保存路径{os.path.abspath(model_path)}")


if __name__ == '__main__':
    bdm = BrainDrainModel('../data/train.csv')
    feature_data, feature_columns = feature_engineering(bdm.data_source, bdm.logfile)
    #print(feature_columns)
    #model_train_lightgbm(feature_data, feature_columns, bdm.logfile)
    model_train_SMOTE(feature_data, feature_columns, bdm.logfile)
